package com.gao.controller;

import com.gao.pojo.User;
import com.gao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @Author: ShanYuqing
 * @Version: v1.0
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public ModelAndView findAll() {
        ModelAndView mv = new ModelAndView("show");
        List<User> list = this.userService.findAll();
        mv.addObject("list", list);
        return mv;
    }


    @GetMapping("/add")
    public String addPage() {
        return "add";
    }

    @PostMapping("/user")
    public String addUser(User user) {
        userService.addUser(user);
        return "redirect:/user";
    }

    @GetMapping("/user/{id}")
    public ModelAndView findUserById(@PathVariable("id")Long id) {
        ModelAndView mv = new ModelAndView("update");
        System.out.println(id);
        User user =this.userService.findUserById(id);
        mv.addObject(user);
        return mv;
    }

    @PostMapping("/update")
    public String updateUser(User user) {
        userService.updateUser(user);
        return "redirect:/user";
    }

    @GetMapping("/delUser/{id}")
    public String delUserById(@PathVariable("id")Long id) {
        userService.delUserById(id);
        return "redirect:/user";
    }
}
